package com.gx.smart.base;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import com.blankj.utilcode.util.BarUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * 基础activity
 */

public abstract class BaseMVVMRefreshActivity<T extends ViewBinding, VM extends BaseViewModel> extends AppCompatActivity
        implements OnRefreshListener, OnLoadMoreListener {
    public static final int PAGE_SIZE = 10;
    protected VM viewModel;
    protected T binding;
    protected int currentPage = 1;
    private RefreshLayout refreshLayout;
    private View noDataView;
    private RecyclerView recyclerView;
    private BaseAdapter adapter;
    private boolean isBackRefresh = false;//返回刷新

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initStatusBar();
        binding = onBindViewBinding(getLayoutInflater());
        setContentView(binding.getRoot());
        initViewModel();
        initView();
        initContent();
        initData();
        initObserver();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (isBackRefresh) {
            this.refreshLayout.autoRefresh();
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        currentPage = 1;
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        currentPage++;
    }


    private void initViewModel() {
        viewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get(onBindViewModel());
    }


    protected void initStatusBar() {
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT);
    }


    protected void initView() {

    }

    /**
     * 使用viewBinding
     */
    protected void initView(RecyclerView recyclerView, BaseAdapter adapter, RefreshLayout refreshLayout, View noDataView) {
        this.refreshLayout = refreshLayout;
        this.refreshLayout.setOnRefreshListener(this);
        this.refreshLayout.setOnLoadMoreListener(this);
        this.noDataView = noDataView;
        this.recyclerView = recyclerView;
        this.adapter = adapter;
        this.recyclerView.setAdapter(adapter);
    }


    protected void initContent() {

    }

    protected void initData() {
    }

    protected void initObserver() {
        viewModel.error.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean result) {
                if (result) {
                    handleErrorResult();
                }
            }
        });
    }

    protected void setBackRefresh() {
        this.isBackRefresh = true;
    }

    protected abstract Class<VM> onBindViewModel();

    protected abstract T onBindViewBinding(@NonNull LayoutInflater inflater);

    protected void registerEventBus() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    protected void unregisterEventBus() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().removeAllStickyEvents();
            EventBus.getDefault().unregister(this);
        }
    }

    /**
     * 初始化title
     *
     * @param title 标题
     */
    protected void initTitle(Toolbar title) {
        setSupportActionBar(title);
        ActionBar ab = getSupportActionBar();
        if (ab != null) {
            ab.setDisplayShowHomeEnabled(true);
            ab.setHomeAsUpIndicator(R.mipmap.ic_arrow_left);
            ab.setDisplayHomeAsUpEnabled(true);
            ab.setTitle("");
        }
    }

    protected void initTitle() {
//     rootBinding.viewStubToolbar.getViewStub().setLayoutResource(onBindTitleLayout());
    }

    private void initLoading() {

    }

    private void initNoData() {

    }

    protected void showLoading() {

    }

    protected void showNoData() {

    }

    protected int onBindTitleLayout() {
        return R.layout.common_toolbar;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 处理请求返回后统一的分页和加载更多处理
     *
     * @param list
     */
    protected void handleResult(List list) {
        if (refreshLayout == null || noDataView == null) {
            return;
        }

        if (currentPage == 1) {
            refreshLayout.finishRefresh();
        }

        if (list.isEmpty() && currentPage == 1) {
            noDataView.setVisibility(View.VISIBLE);
            refreshLayout.setEnableLoadMore(false);
            return;
        }
        if (list.size() < PAGE_SIZE) {
            refreshLayout.finishLoadMoreWithNoMoreData();
        } else {
            refreshLayout.finishLoadMore();
            refreshLayout.setEnableLoadMore(true);
        }

        if (noDataView.getVisibility() == View.VISIBLE) {
            noDataView.setVisibility(View.GONE);
        }

        if (currentPage == 1) {
            adapter.clear();
        }
        adapter.addAll(list);
    }


    private void handleErrorResult() {
        if (refreshLayout == null || noDataView == null) {
            return;
        }
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (currentPage == 1) {
            refreshLayout.setEnableLoadMore(false);
        }
        noDataView.setVisibility(View.VISIBLE);
    }

}